package com.netx.cubigraf.shared;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletConfig;
import com.netx.generics.basic.Context;
import com.netx.generics.basic.Property;
import com.netx.generics.io.FileSystem;
import com.netx.generics.io.Location;
import com.netx.generics.tasks.TaskManager;
import com.netx.ebs.InitializerServlet;


public class ApplicationInitializer extends InitializerServlet {

	public ApplicationInitializer() {
		super();
	}
	
	public void ebsInit(ServletConfig config) throws Throwable {
		super.ebsInit(config);
		getLogger().info("starting application "+getEbsContext().getApplicationName()+"... ");
		Context.getRootContext().setProperty("task-manager", new TaskManager(5));
		// Load servers from 'config-shared.xml':
		Context servers = Context.getRootContext().getContext("servers");
		Iterator<Property> it = servers.getProperties().iterator();
		while(it.hasNext()) {
			Property p = it.next();
			if(p.objectValue() instanceof Location) {
				try {
					servers.setProperty(p.getName(), new FileSystem((Location)p.objectValue()));
				}
				catch(IOException io) {
					addInitError(io);
				}
			}
		}
		getLogger().info("application started");
	}

	public void ebsDestroy() throws Throwable {
		getLogger().info("exited application "+getEbsContext().getApplicationName());
		TaskManager tm = (TaskManager)Context.getRootContext().getProperty("task-manager").objectValue();
		tm.stop();
		super.ebsDestroy();
	}
}
